const fs = require('fs');
const glob = require('glob');
const HtmlWebpackPlugin = require('html-webpack-plugin');

// 引入页面css文件
function getCssFile(fileName) {
  let cssFile;
  const cssPath = `css/${fileName.split('.')[0]}.css`;
  if (fs.existsSync(`src/${cssPath}`)) {
    cssFile = `<link rel="stylesheet" href="./${cssPath}" />`;
  }
  return cssFile;
}

// 引入页面js文件
function getJsFile(fileName) {
  let jsFile;
  const n = fileName.split('.')[0];
  const jsPath = `js/${n}/${n}.js`;
  if (fs.existsSync(`src/${jsPath}`)) {
    jsFile = `<script src="./${jsPath}"></script>`;
  }
  return jsFile;
}

// 获取所有模板
function getTemplate() {
  const files = glob.sync('src/template/**.html');
  const templates = {};
  files.forEach(async (filePath) => {
    const arr = filePath.split('/');
    const templateName = arr[arr.length - 1];
    const name = templateName.split('.')[0];
    templates[name] = fs.readFileSync(filePath, 'utf8');
  });
  return templates;
}

// 获取所有模板配置数据
function getData() {
  const files = glob.sync('src/data/**.json');
  const data = {};
  files.forEach(async (filePath) => {
    const arr = filePath.split('/');
    const dataName = arr[arr.length - 1];
    const name = dataName.split('.')[0];
    const dd = fs.readFileSync(filePath, 'utf8');
    data[name] = JSON.parse(dd);
  });
  return data;
}

// 设置所有页面文件
function BuildHtml() {
  const files = glob.sync('src/**.html');
  const htmlWebpack = [];
  const templates = getTemplate();
  const data = getData();

  files.forEach((filePath, index) => {
    const arr = filePath.split('/');
    const fileName = arr[arr.length - 1];
    let main = fs.readFileSync(filePath, 'utf8');

    // 开发环境
    if (process.env.npm_lifecycle_event == 'serve') {
    }

    htmlWebpack.push(
      new HtmlWebpackPlugin({
        inject: false,
        title: '欧球',
        htmlName: fileName,
        data: data[fileName.split('.')[0]],
        tags: {
          main: main,
          // css: getCssFile(fileName),
          // js: getJsFile(fileName),
          ...templates,
        },
        filename: fileName,
        template: filePath,
        // template: "src/public/index.html",
      }),
    );
  });

  return htmlWebpack;
}

module.exports = BuildHtml;
